package com.addjava.demo;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.addjava.demo.view.PageviewerAdapter;

public class ScrolltestActivity extends Activity implements OnTouchListener, OnPageChangeListener {

	ScrollView scroll_main;

	LayoutInflater inflater;
	ViewPager main_viewpager;
	LinearLayout ll_main;
	//
	private TextView mRefreshViewText;
	private ImageView mRefreshViewImage;
	private ProgressBar mRefreshViewProgress;
	private RotateAnimation mFlipAnimation;
	private RotateAnimation mReverseFlipAnimation;

	private int mRefreshState = 1;
	private static final int PULL_TO_REFRESH = 1;
	private static final int RELEASE_TO_REFRESH = 2;

	boolean iskeydown = false;
	private float starty = 0;

	private TextView textView_inpage0;
	private TextView textView_inpage1;

	private int currentPageIndex = 0 ;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.scrolltest);

		inflater = getLayoutInflater();

		intiview();
		initListener();
	}

	void intiview() {
		scroll_main = (ScrollView) findViewById(R.id.scroll_main);
		main_viewpager = (ViewPager) findViewById(R.id.main_viewpager);
		ll_main = (LinearLayout) findViewById(R.id.ll_main);

		mRefreshViewText = (TextView) findViewById(R.id.pull_to_refresh_text);
		mRefreshViewImage = (ImageView) findViewById(R.id.pull_to_refresh_image);
		mRefreshViewProgress = (ProgressBar) findViewById(R.id.pull_to_refresh_progress);
		mRefreshViewProgress.setVisibility(View.GONE);
		mRefreshViewImage.setMinimumHeight(45);
		mRefreshState = PULL_TO_REFRESH;

		// Load all of the animations we need in code rather than through XML
		mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		mFlipAnimation.setInterpolator(new LinearInterpolator());
		mFlipAnimation.setDuration(250);
		mFlipAnimation.setFillAfter(true);

		mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		mReverseFlipAnimation.setInterpolator(new LinearInterpolator());
		mReverseFlipAnimation.setDuration(250);
		mReverseFlipAnimation.setFillAfter(true);

	}

	void initListener() {
		scroll_main.setOnTouchListener(this);
		ArrayList<View> main_viewpagercontent = new ArrayList<View>();
		View v1 = inflater.inflate(R.layout.t1, null);
		main_viewpagercontent.add(v1);
		textView_inpage0 =(TextView) v1.findViewById(R.id.textView_inpage1) ;
		
		View v2 = inflater.inflate(R.layout.t2, null);
		main_viewpagercontent.add(v2);
		textView_inpage1 =(TextView) v2.findViewById(R.id.textView_inpage2) ;
		
		main_viewpager.setAdapter(new PageviewerAdapter(main_viewpagercontent));
		
		main_viewpager.setOnPageChangeListener(this);
		
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		float currenty = event.getY();
		switch (event.getAction()) {
		// 发现一个比较奇怪的问题. 就是 嵌套 了ViewPager 后 scrollview 的 onTouch
		// MotionEvent.ACTION_DOWN 就不起作用了...
		// 所以只能临时使用 iskeydown 来完成. 不知道有什么好的办法解决
		case MotionEvent.ACTION_DOWN:
			break;
		case MotionEvent.ACTION_MOVE:
			if (!iskeydown) {
				iskeydown = true;
				starty = event.getY();
			}
			Log.i("ACTION_MOVE", "starty=" + starty + "|currenty=" + currenty);
			int topPadding = (int) ((currenty - starty) / 1.7);
			if (topPadding >= 0) {
				if (topPadding <= 60) {
					if (mRefreshState == RELEASE_TO_REFRESH) {
						mRefreshState = PULL_TO_REFRESH;
						mRefreshViewImage.clearAnimation();
						mRefreshViewText.setText("下拉刷新");
						mRefreshViewImage.startAnimation(mReverseFlipAnimation);
					}
				} else {
					if (mRefreshState == PULL_TO_REFRESH && v.getScrollY() >= 0 && v.getScrollY() <= 2) {
						mRefreshState = RELEASE_TO_REFRESH;
						mRefreshViewImage.clearAnimation();
						mRefreshViewText.setText("松开刷新");
						mRefreshViewImage.startAnimation(mFlipAnimation);
					}
				}
				showheader(currenty);
			}

			break;
		case MotionEvent.ACTION_UP:
			Log.i("ACTION_UP", "ACTION_UP run");
			// 可以触发刷新事件了
			if (mRefreshState == RELEASE_TO_REFRESH) {
				new RefreshTask().execute();
			} else {
				hideheader();
			}
			iskeydown = false;
			break;
		}
		return true;
	}

	private void showheader(float currenty) {
		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ll_main.getLayoutParams();
		int margin = (int) (currenty - starty);
		params.setMargins(0, margin, 0, 0);
		ll_main.setLayoutParams(params);
	}

	private void hideheader() {
		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) ll_main.getLayoutParams();
		params.setMargins(0, 0, 0, 0);
		ll_main.setLayoutParams(params);
	}

	public class RefreshTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			mRefreshViewImage.clearAnimation();
			mRefreshViewText.setText("正在刷新");
			mRefreshViewImage.setVisibility(View.GONE);
			mRefreshViewProgress.setVisibility(View.VISIBLE);
			scroll_main.setEnabled(false);
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				Thread.sleep(2000);
				// Do your task
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			mRefreshViewProgress.setVisibility(View.GONE);
			hideheader();
			mRefreshViewText.setText("下拉刷新");
			mRefreshViewImage.setVisibility(View.VISIBLE);
			scroll_main.setEnabled(true);
			mRefreshState = PULL_TO_REFRESH;
			super.onPostExecute(result);
			
			if (currentPageIndex==0) {
				textView_inpage0.setText("update at ="+Calendar.getInstance().getTime());
			}else if (currentPageIndex==1) {
				textView_inpage1.setText("update at ="+Calendar.getInstance().getTime());
				
			}
			
			
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int arg0) {
		currentPageIndex = arg0 ;
		// TODO Auto-generated method stub
		System.out.println("page["+arg0+"] is selected!");
		main_viewpager.getCurrentItem() ;
	}

}